package top.kaoshanji.q1ch06a;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import top.kaoshanji.q1ch06a.aspects.LoggingAspect;
import top.kaoshanji.q1ch06a.config.ProjectConfig;
import top.kaoshanji.q1ch06a.model.Comment;
import top.kaoshanji.q1ch06a.services.CommentService;

import java.util.logging.Logger;

/**
 * @author kaoshanji
 * ^_^
 * create time 2025/4/28 17:57
 */
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {ProjectConfig.class})
public class AppTests {

    private Logger serviceLogger;
    private Logger aspectLogger;

    @Autowired
    private LoggingAspect loggingAspect;

    @Autowired
    private CommentService commentService;

    @BeforeEach
    public void before() {
        this.aspectLogger = Mockito.mock(Logger.class); // 创建一个对象
        loggingAspect.setLogger(aspectLogger); // 赋值

        this.serviceLogger = Mockito.mock(Logger.class);
        commentService.setLogger(serviceLogger);

    }

    /**
     * 代码清单test-q1ch06a-01：测试一下实现简单的切面
     */
    @Test
    public void testAspectInterceptsPublishCommentMethod() {
        Comment comment = new Comment();
        comment.setText("Test comment text");
        comment.setAuthor("Test comment author");

        commentService.publishComment(comment);

        Mockito.verify(serviceLogger).info("发布一个 Comment：" + comment.getText());

        Mockito.verify(aspectLogger, Mockito.atLeastOnce()).info("...方法执行前调用....");
        Mockito.verify(aspectLogger, Mockito.atLeastOnce()).info("...方法执行后调用....");

    }


}
